const config = {
	// baseURL: 'http://linyuhang.vip:4000',
	baseURL: 'http://47.104.174.167:4000',
	// baseURL: 'http://localhost:3000',
	timeout: 10000,
	withCredentials: true
};
const cookie = "MUSIC_U=64e8b473cb61f7a55f88a3c771f6c0f10771e18fad843d0435c151ca0abc2f0fc4d7ae04c67cbcdb66c653e254108c40ed48a27fe04c3bb0; __remember_me=true; __csrf=2705802ec2e5a3d8bb67095d83021274; path=/"

import axios from 'axios';
var axiosCookie = axios.create(config);
var axiosLoading = axios.create(config);
axiosLoading.interceptors.request.use(function (config) {
	uni.showLoading({
		title: '请求中...'
	})
	// uni.startPullDownRefresh();
	return config;
});
axiosLoading.interceptors.response.use(function (res) {
	uni.hideLoading();
	// setTimeout(() => {
	// 	uni.stopPullDownRefresh();
	// }, 1000);
	return res;
});

function promise(url, data, loading){
	// #ifdef H5
	let axios = axiosCookie;
	if (loading) {
		axios = axiosLoading;
	}
	return new Promise((resolve, reject) => {
		axios.get(url, {
			params: {
				...data,
				cookie: uni.getStorageSync('cookie') || cookie
			},
		}).then(response => {
			if (response.status === 200) {
				resolve(response.data);
			} else if (response.status === 502) {
				uni.showToast({
					title: response.data.msg,
					duration: 1500
				})
				reject(response.data);
			} else {
				reject(response.data);
			}
		}, err => {
			reject(err)
		})
		.catch((error) => {
			reject(error)
		})
	})
	// #endif
	// #ifndef H5
	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '请求中...',
				mask: true,
			});
			// uni.startPullDownRefresh();
		}
		uni.request({
			withCredentials: true,
			url: config.baseURL + url,
			data: {
				...data,
				cookie: uni.getStorageSync('cookie') || cookie
			},
			complete: (res) => {
				if (loading) {
					uni.hideLoading();
					// setTimeout(() => {
					// 	uni.stopPullDownRefresh();
					// }, 1000);
				}
				if (res.statusCode === 200) {
					if (res.header['Set-Cookie']) {
						uni.setStorage({
							key: 'cookie',
							data: res.header['Set-Cookie'],
							success: function () {
								resolve(res.data);
							}
						});
					} else {
						resolve(res.data);
					}
				} else if (res.statusCode === 502) {
					uni.showToast({
						title: res.data.msg,
						duration: 1500
					})
					reject(res.data);
				} else {
					reject(res.data);
				}
			}
		});
	});
	// #endif
}
function request(url, data) {
	return promise(url, data, true);
}
request.noloading = function(url, data) {
	return promise(url, data, false);
}
export default request;